package com.wd.good.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @description: 动态代理
 * @author wangdpng
 * @date 2023/11/18 10:31
 */
public class RetryInvocationHandler implements InvocationHandler {
    private Object subject;

    public RetryInvocationHandler(Object subject) {
        this.subject = subject;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        int times = 1;
        while (times <= 5) {
            try{
                int i = 3/0;
                method.invoke(subject,args);
            }catch (RuntimeException e){
                System.out.println("调用动态代理，重试次数"+ times +"次");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
                times++;
                if (times > 5) {
                    throw new RuntimeException("重试次数超过5次");
                }
            }
        }
        return null;
    }

    public static Object getProxy(Object realSubject){
        RetryInvocationHandler handler = new RetryInvocationHandler(realSubject);
        return Proxy.newProxyInstance(handler.getClass().getClassLoader(), realSubject.getClass().getInterfaces(), handler);
    }
}
